package com.canbot.u05.helper

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
import com.canbot.u05.R

/**
 * Created by zmp on 2019/4/8 16:24
 *
 * @author zmp
 */
class RoadRecyclerDecoration(context: Context) : RecyclerView.ItemDecoration() {

    private val dimension: Float = context.resources.getDimension(R.dimen.px2)
    private val mPaint: Paint = Paint()

    init {
        mPaint.strokeWidth = dimension
        mPaint.isAntiAlias = true
        mPaint.color = Color.parseColor("#2A375E")
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        val index = parent.getChildAdapterPosition(view)
        val itemCount = parent.adapter?.itemCount ?: 0
        if (index != itemCount - 1) {
            outRect.bottom = dimension.toInt()
        } else {
            outRect.bottom = 0
        }
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val childCount = parent.childCount
        val paddingBottom = parent.paddingBottom
        val top = parent.top
        val parentBottom = parent.bottom
        val minBottom = parentBottom - top - paddingBottom
        for (i in 0 until childCount) {
            val view = parent.getChildAt(i)
            val bottom = view.bottom.toFloat()
            if (bottom > minBottom) {
                continue
            }
            c.drawLine(view.left.toFloat(), bottom + dimension / 2, view.right.toFloat(), bottom + dimension / 2, mPaint)
        }
    }
}
